#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RAG系统调试脚本
"""

import sys
import os
import json

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def debug_rag_system():
    print("=" * 60)
    print("RAG系统调试诊断")
    print("=" * 60)
    
    # 1. 检查Python环境
    print("1. Python环境检查:")
    print(f"   Python版本: {sys.version}")
    print(f"   当前工作目录: {os.getcwd()}")
    print(f"   Python路径: {sys.path[:3]}...")
    
    # 2. 检查文件是否存在
    print("\n2. 文件检查:")
    files_to_check = [
        'simple_rag_system.py',
        'rag_system.py',
        'app_new.py',
        'knowledge_base'
    ]
    
    for file in files_to_check:
        if os.path.exists(file):
            print(f"   ✓ {file} - 存在")
        else:
            print(f"   ✗ {file} - 不存在")
    
    # 3. 测试模块导入
    print("\n3. 模块导入测试:")
    
    # 测试简化版RAG系统
    try:
        from simple_rag_system import SimpleRAGSystem
        print("   ✓ SimpleRAGSystem - 导入成功")
        
        # 测试初始化
        rag = SimpleRAGSystem()
        print("   ✓ SimpleRAGSystem - 初始化成功")
        
        # 测试基本功能
        stats = rag.get_knowledge_stats()
        print(f"   ✓ 知识库统计: {stats['total_knowledge']}条知识")
        
        # 测试问答
        result = rag.get_answer("测试问题")
        print(f"   ✓ 问答功能: 置信度 {result['confidence']:.2f}")
        
    except Exception as e:
        print(f"   ✗ SimpleRAGSystem - 失败: {e}")
        import traceback
        traceback.print_exc()
    
    # 4. 检查知识库文件
    print("\n4. 知识库文件检查:")
    kb_file = os.path.join('knowledge_base', 'knowledge_base.json')
    if os.path.exists(kb_file):
        try:
            with open(kb_file, 'r', encoding='utf-8') as f:
                kb_data = json.load(f)
            print(f"   ✓ 知识库文件存在，包含 {len(kb_data)} 条知识")
        except Exception as e:
            print(f"   ✗ 知识库文件读取失败: {e}")
    else:
        print("   ✗ 知识库文件不存在")
    
    # 5. 测试Flask应用导入
    print("\n5. Flask应用测试:")
    try:
        import flask
        print(f"   ✓ Flask版本: {flask.__version__}")
        
        # 尝试导入app_new
        from app_new import app, rag_system, RAG_AVAILABLE
        print(f"   ✓ Flask应用导入成功")
        print(f"   ✓ RAG_AVAILABLE: {RAG_AVAILABLE}")
        print(f"   ✓ rag_system: {'已初始化' if rag_system else '未初始化'}")
        
    except Exception as e:
        print(f"   ✗ Flask应用导入失败: {e}")
        import traceback
        traceback.print_exc()
    
    print("\n" + "=" * 60)
    print("调试完成")
    print("=" * 60)

if __name__ == "__main__":
    debug_rag_system()
    input("\n按回车键退出...")
